const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
const PENDING = 'pending';
class HYPromise {
    constructor(executor) {
        this.status = PENDING;
        this.value = undefined;
        this.reason = undefined;
        this.onFulfilledFns = [];
        this.onRejectedFns = [];
        const resolve = (value) => {
            this.status = FULFILLED;
            this.value = value;
            this.onFulfilledFns.forEach(fn => fn(this.value));
        };
        const reject = (reason) => {
            this.status = REJECTED;
            this.reason = reason;
            this.onRejectedFns.forEach(fn => fn(this.reason));
        };
        try {
            executor(resolve, reject);
        } catch (err) {
            console.log(new Error(err));
        }
    };
    then(onFulfilled, onRejected) {
        return new HYPromise((resolve, reject) => {
            if (this.status === FULFILLED) {
                try {
                    const value = onFulfilled(this.value);
                    resolve(value);
                } catch (err) {
                    reject(err);
                }
            }
            if (this.status === REJECTED) {
                try {
                    const reason = onRejected(this.reason);
                    resolve(reason);
                } catch (err) {
                    reject(err);
                }
            }
            if (this.status === PENDING) {
                this.onFulfilledFns.push(() => {
                    try {
                        const value = onFulfilled(this.value);
                        resolve(value);
                    } catch (err) {
                        reject(err);
                    }

                });
                this.onRejectedFns.push(() => {
                    try {
                        const reason = onRejected(this.reason);
                        resolve(reason);
                    } catch (err) {
                        reject(err);
                    }

                });
            }
        });
    }
};
const p1 = new Promise((resolve, reject) => {
    // setTimeout(() => {
    //     resolve("11");
    // }, 2000)
    resolve(1);

});

const p2 = new HYPromise((resolve, reject) => {
    // setTimeout(() => {
    //     resolve("22");
    // }, 2000)
    resolve(2);
});

p1.then(res => {
    console.log(res);
    return "mm";
}).then(res => {
    console.log(res);
});
console.log("这里是pi后面");
p2.then(res => {
    console.log(res);
    return "nn";
}).then(res => {
    console.log(res);
});
console.log("这里是p2后面");